const app = getApp();

Page({
  data: {
    userInfo: null,
    hasUserInfo: false,
    showLoginButton: true,
    showDetails: false,
    showLogs: true,
    logs: []
  },
  
  onLoad: function() {
    console.log('首页加载，检查用户登录状态');
    if (app.globalData.userInfo) {
      console.log('已有用户信息:', app.globalData.userInfo.nickName);
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        showLoginButton: false
      });
    } else {
      console.log('未检测到用户信息');
    }
  },
  
  onShow() {
    // 每次页面显示时检查登录状态
    if (app.globalData.isLoggedIn) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        showLoginButton: false
      });
    } else {
      this.setData({
        userInfo: null,
        hasUserInfo: false,
        showLoginButton: true
      });
    }
  },
  
  // 处理登录
  handleLogin() {
    wx.showLoading({
      title: '登录中...',
    });

    // 调用全局登录方法
    getApp().login()
      .then(userInfo => {
        this.setData({
          userInfo: userInfo,
          hasUserInfo: true,
          showLoginButton: false
        });
        wx.hideLoading();
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });
      })
      .catch(err => {
        console.error('登录失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '登录失败',
          icon: 'error'
        });
      });
  },
  
  // 切换用户详情显示状态
  toggleDetails: function() {
    this.setData({
      showDetails: !this.data.showDetails
    });
    console.log('切换用户详情显示:', this.data.showDetails);
  },
  
  // 复制用户信息到剪贴板
  copyUserInfo: function() {
    const userInfo = this.data.userInfo;
    if (!userInfo) return;
    
    const userInfoText = JSON.stringify({
      nickName: userInfo.nickName || '未获取',
      gender: userInfo.gender === 1 ? '男' : (userInfo.gender === 2 ? '女' : '未知'),
      code: userInfo.code || '未获取',
      province: userInfo.province || '',
      city: userInfo.city || ''
    }, null, 2);
    
    wx.setClipboardData({
      data: userInfoText,
      success: () => {
        wx.showToast({
          title: '用户信息已复制',
          icon: 'success'
        });
        console.log('用户信息已复制到剪贴板');
      },
      fail: (err) => {
        console.error('复制用户信息失败:', err);
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 扫描二维码
  handleScan: function() {
    // 确保用户已登录
    if (!this.data.hasUserInfo) {
      console.log('用户未登录，先进行登录');
      this.handleLogin();
      return;
    }
    
    console.log('用户点击扫码按钮');
    wx.scanCode({
      success: (res) => {
        console.log('扫码成功，结果:', res.result);
        try {
          const qrcodeData = JSON.parse(res.result);
          console.log('解析二维码数据:', qrcodeData);
          
          if (qrcodeData && qrcodeData.qrcodeId) {
            console.log('解析到二维码ID:', qrcodeData.qrcodeId);
            // 跳转到扫码确认页面
            wx.navigateTo({
              url: `/pages/scan/scan?qrcodeId=${qrcodeData.qrcodeId}`
            });
          } else {
            console.error('二维码数据不完整:', qrcodeData);
            wx.showToast({
              title: '无效的二维码',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('解析二维码失败:', error);
          console.error('原始二维码内容:', res.result);
          wx.showToast({
            title: '无效的二维码格式',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('扫码失败:', err);
        if (err.errMsg !== 'scanCode:fail cancel') {
          wx.showToast({
            title: '扫码失败，请重试',
            icon: 'none'
          });
        }
      }
    });
  },

  // 处理退出登录
  handleLogout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          app.logout();
          this.setData({
            userInfo: null,
            hasUserInfo: false,
            showLoginButton: true
          });
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  // 添加日志
  addLog(message, data = null) {
    const timestamp = new Date().toLocaleTimeString();
    const log = {
      time: timestamp,
      message: data ? `${message}: ${JSON.stringify(data)}` : message
    };
    
    const logs = this.data.logs;
    logs.push(log);
    
    this.setData({ logs });
  },

  // 复制日志
  copyLogs() {
    const logsText = JSON.stringify(this.data.logs, null, 2);
    wx.setClipboardData({
      data: logsText,
      success: () => {
        wx.showToast({
          title: '日志已复制',
          icon: 'success'
        });
      }
    });
  }
}); 